import java.util.Arrays;

class MyemptyStackException extends RuntimeException{
    public MyemptyStackException() {
    }

    public MyemptyStackException(String message) {
        super(message);
    }
}
public class MyStack {
    public int[] elem;//定义的数组
    public int usedSize;//栈的元素个数
    public static final int DEFAULT_SIZE = 10;

    public MyStack() {
        this.elem = new int[DEFAULT_SIZE];
    }

    /*
    * NO.1
    * @ 压栈
    * */
    public int push(int val) {
        if (isFull()) {
            //扩容
            elem = Arrays.copyOf(elem, 2 * elem.length);//扩2倍
        }
        this.elem[this.usedSize] = val;//从栈顶压入元素
        this.usedSize++;//元素个数加1
        return val;
    }

    public boolean isFull(){
        return this.usedSize == elem.length;//当前栈中元素个数等不等于数组的大小
    }

    /*
    * NO.2
    * @ 出栈
    * */
    public int pop() throws MyemptyStackException{
        if (isEmpty()) {
            //抛异常
            throw new MyemptyStackException("栈为空！！！");
        }
        /*int ret = this.elem[this.usedSize - 1];
        this.usedSize--;//栈顶的位置减一个
        return ret;//返回栈顶的下标*/

        //简化
        return this.elem[--this.usedSize];
    }

    public boolean isEmpty() {
        return this.usedSize == 0;//为真就是空
    }

    /*
    * NO.3
    * @ 看一眼元素，但不拿出
    * */
    public int peek() throws MyemptyStackException{
        if (isEmpty()) {
            throw new MyemptyStackException("栈为空！！！");
        }
        return this.elem[this.usedSize - 1];//栈顶的位置不需要减一个
    }

    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(10);
        myStack.push(20);
        myStack.push(30);
        myStack.push(40);
        int stackTop = myStack.pop();//拿出此时的栈顶元素
        System.out.println(stackTop);//打印栈顶元素 - 40

        stackTop = myStack.pop();
        System.out.println(stackTop);// 30

        stackTop = myStack.pop();
        System.out.println(stackTop);//20

        int stackPeek = myStack.peek();
        System.out.println(stackPeek);//打印此时的栈顶元素 - 但不拿出
        System.out.println(stackPeek);//此时的栈顶韩还是10
    }
}
